<template>
  <div>
    <span v-if="!editable">{{enumLabel}}</span>
    <el-radio-group v-if="editable" v-model="enumValue" @change="selectOption">
      <el-radio
        v-for="item in options"
        :key="item.value"
        :label="item.value">
        {{item.label}}
      </el-radio>
    </el-radio-group>
  </div>
</template>

<script>
  export default {
    name: "FtRadioGroup",
    props: {
      serviceName: {
        type: String
      },
      typeName: {
        type: String,
        default: null
      },
      value: {
        type: [String, Number]
      },
      editable: {
        type: Boolean,
        default: true
      },
      disabled: {
        type: Boolean,
        default: false
      }
    },
    mounted() {
      this.load()
    },
    data() {
      return {
        options: [],
        enumValue: null
      }
    },
    methods: {
      load() {
        this.options = []
        this.enumValue = null
        if (this.serviceName && this.typeName) {
          this.$http.get('/joys-rest/' + this.serviceName + '/enums/' + this.typeName + '/items').then(
            resp => {
              this.options = resp.body || []
              this.loadValue()
            }, resp => {
              this.$message.error('查询失败')
            }
          )
        }
      },
      selectOption() {
        this.$emit('input', this.enumValue)
        this.$emit('change', this.enumValue)
      },
      loadValue() {
        const enumItem = this.options && this.options.find((item) => {
          return item.value === this.value
        })
        this.enumValue = enumItem && enumItem.value
      }
    },
    computed: {
      enumLabel() {
        const enumItem = this.options && this.options.find((item) => {
          return item.value === this.enumValue
        })
        return enumItem ? enumItem.label : ''
      }
    },
    watch: {
      value() {
        this.loadValue()
      },
      serviceName() {
        this.load()
      },
      typeName() {
        this.load()
      }
    }
  }
</script>

<style scoped>

</style>
